package threadPool;

import Utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Slf4j
public class ThreadMonitor {
    private static Set<String> threadNamePool = new HashSet<>(8);


    public static void registerThreadNamePool(String name) {
        threadNamePool.add(name);
    }

    /***
     * 获取线程池信息
     * @param name
     * @return
     */
    public static List<LinkedHashMap> get(String name) {
        List list = new ArrayList<>(4);
        if (StringUtils.isNotEmpty(name)) {
            ThreadPoolExecutorMdcWrapper threadPoolExecutorMdcWrapper = null;
            try {
                threadPoolExecutorMdcWrapper = (ThreadPoolExecutorMdcWrapper) SpringContextUtils.getBean(name);
            } catch (Exception e) {
                log.error("ThreadMonitor_error:{}", e.getMessage(), e);
            }
            if (threadPoolExecutorMdcWrapper == null) {
                return null;
            }
            list.add(threadPoolExecutorMdcWrapper.monitor());
        } else {
            threadNamePool.forEach(t -> {
                ThreadPoolExecutorMdcWrapper threadPoolExecutorMdcWrapper = null;
                try {
                    threadPoolExecutorMdcWrapper = (ThreadPoolExecutorMdcWrapper) SpringContextUtils.getBean(t);
                } catch (Exception e) {
                    log.error("ThreadMonitor_error:{}", e.getMessage(), e);
                }
                if (threadPoolExecutorMdcWrapper != null) {
                    list.add(threadPoolExecutorMdcWrapper.monitor());
                }

            });
        }
        return list;
    }


    /***
     * 动态修改线程池
     *   目前仅支持  ThreadPoolExecutorMdcWrapper
     * @param name
     * @param corePoolSize
     * @param maximumPoolSize
     * @return
     */
    public static LinkedHashMap set(String name, int corePoolSize, int maximumPoolSize) {
        ThreadPoolExecutorMdcWrapper threadPoolExecutorMdcWrapper = null;
        try {
            threadPoolExecutorMdcWrapper = (ThreadPoolExecutorMdcWrapper) SpringContextUtils.getBean(name);
            threadPoolExecutorMdcWrapper.setCorePoolSize(corePoolSize);
            threadPoolExecutorMdcWrapper.setMaximumPoolSize(maximumPoolSize);
        } catch (Exception e) {
            log.error("ThreadMonitor_error:{}", e.getMessage(), e);
            throw  e;

        }

        return threadPoolExecutorMdcWrapper.monitor();
    }
}
